package cn.jdy.plugins.admin;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.plugins.entity.Research;
import cn.jdy.plugins.service.ResearchService;

/**
 * @author yym
 * @title 通知通报控制类
 * @date 2016/02/16
 */
@Controller
@RequestMapping("/research")
public class ResearchCtrl extends BaseCtrl {

	@Autowired
	private ResearchService researchService;
	//默认列表路径
	private static String viewName = "redirect:/research/list?s=";

	/**
	 * 初始化
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(Research entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/researchList.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "保存成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		return mv;
	}

	/**
	 * 异步查询
	 * @param news
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(Research research, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", researchService.query(research, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", researchService.count(research, fromDate, toDate));
			jsonMap.put("iTotalRecords", researchService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/researchDetail.jsp");
//		mv.addObject("data", id==null||id==0 ? id : this.researchService.find(id));
		if(id==null || id==0){
			mv.addObject("data", id);
		}else{
			Research research = this.researchService.find(id);
			//投稿统计师将department置null,现将其复原到页面回显
			String[] nd = research.getAssociations();
			if(nd == null){
				String temp=research.getDepars();
				String[] st=temp.split(",");
				int cnt=st.length;
				String[] nds = new String[cnt-1];
				for(int i=1;i<cnt;i++){
					nds[i-1]=st[i];
				}
				research.setAssociations(nds);;
			}
			mv.addObject("data", research);
		}
		return mv;
	}

	/**
	 * 保存（更新）新闻
	 * @param news
	 * @return
	 */
	@RequestMapping("/save")
	public ModelAndView save(Research research, Long pid) {
		ModelAndView mv = new ModelAndView();
		//将数组转化成String
		String[] ds=research.getAssociations();
		String deps = "";
		for(int i=0;i<46;i++){
			if(ds[i]==null || ds[i]=="")ds[i]=";";
			deps += ","+ds[i];
		}
		research.setDepars(deps);
		research.setAssociations(null);
		
		try {
			if(research.getId()==null) {
				// 新增通知通报
				User user = getUser();
				research.setUserid(user.getId());
				research.setUsername(user.getUsername());
				if(research.getFalseCreateTime() == null || research.getFalseCreateTime() == ""){
					research.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.researchService.save(research);
				mv.setViewName(this.viewName.concat("1"));
			} else {
				//更新修改通知通报
				// 新增通知通报
				User user = getUser();
				research.setUserid(user.getId());
				research.setUsername(user.getUsername());
				if(research.getFalseCreateTime() == null || research.getFalseCreateTime() == ""){
					research.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.researchService.update(research);
				mv.setViewName(this.viewName.concat("2"));
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, research.getId());
			}
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "保存异常！", e);
		}

		return mv;
	}
	
	/**
	 * 删除新闻
	 * @return
	 */
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.researchService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理文章缓存
			NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除异常！", e);
		}
		return mv;
	}

	/**
	 * 襄阳特警
	 * 签收通知通报：多个用户均需要签收
	 * @param id
	 * @param name 登录用户名 String
	 * @return
	 */
	@RequestMapping("/sign/{id}")
	public ModelAndView signed(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/operate/researchList.jsp");
		Research data = this.researchService.find(id);
		if(data.getTeams() == null){
			data.setTeams(name);
			data.setSignStatus("1");
		} else {
			String[] strs = data.getTeams().split(",");
			int cnt=0,len=strs.length;
			for(int i=0;i<len;i++){
				if(!(strs[i].equals(name))){
					cnt++;
				}
			}
			if(cnt>=len){
				data.setTeams(data.getTeams()+","+name);
				data.setSignStatus(data.getSignStatus()+"1");
			}
		}
		this.researchService.update(data);
		return mv;
	}
	
	/**
	 * 市公安局
	 * 复签：只需要发布者一人签收
	 * @param id
	 * @param name
	 * @return
	 */
	@RequestMapping("/counterSign/{id}")
	public ModelAndView ctsigned(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/operate/researchList.jsp");
		Research data = this.researchService.find(id);
		if(name.equals(data.getUsername())){
			data.setSignStatus("1");
		}
		this.researchService.update(data);
		return mv;
	}
	
	/**
	 * 襄阳市公安局
	 * 签收通知通报：多个用户均需要签收
	 * @param id
	 * @param name 登录用户名 String
	 * @return
	 */
	@RequestMapping("/signed/{id}")
	public ModelAndView signeds(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/operate/researchList.jsp");
		Research data = this.researchService.find(id);
		
		String[] assos = data.getDepars().split(",");
		int lens = assos.length;
		String statuses = data.getSignStatus();
		if(statuses==null){
			for(int iter=0;iter<lens;iter++){
				if(assos[iter]!=null && assos[iter].equals(name)){
					data.setSignStatus(name);//将状态1换成用户名
				}
			}
		}else{
			for(int iter=1;iter<lens;iter++){
				//同一账户重复签收无影响
				if(assos[iter]!=null && statuses.indexOf(name)==-1 && assos[iter].equals(name)){
					data.setSignStatus(statuses+","+name);
				}
			}
		}
		this.researchService.update(data);
		return mv;
	}
}
